﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using XQ.WeChatOfficialAccount.DAL.DAL.Common;

namespace XQ.WeChatOfficialAccount.BLL.Common
{
    public class QiXinTongHelper
    {
        static string auth_code = "a37bafe4497c456eae25929cc6558c0f1ca98a27";
        static string spid = "1000043567";
        static string authKey = "ac50a974b0a94a888703299fc0859f2c";

        public static QiXinTongReturnModel SendSMS(string context, string[] phones)
        {
            QiXinTongModel qiXinTongModel = new QiXinTongModel();
            string contextStr = GetUpperEncode(context, Encoding.UTF8);
            DateTime timeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            qiXinTongModel.auth_code = auth_code;
            qiXinTongModel.spid = spid;
            qiXinTongModel.extport = "";
            qiXinTongModel.smsid = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000,9999);
            qiXinTongModel.mobiles = string.Join(",", phones);
            qiXinTongModel.content = contextStr;
            qiXinTongModel.sendtime = "";
            qiXinTongModel.timestamp = (long)(DateTime.Now.ToUniversalTime() - timeStampStartTime).TotalMilliseconds;
            qiXinTongModel.msgfmt = "8";

            string oldParam = qiXinTongModel.auth_code + qiXinTongModel.spid + qiXinTongModel.smsid + qiXinTongModel.mobiles + qiXinTongModel.sendtime + qiXinTongModel.content + qiXinTongModel.timestamp + authKey;
            string sign = SHA1Encryption(oldParam, Encoding.UTF8).ToLower();
            qiXinTongModel.sign = sign;

            string postDataStr = "auth_code={0}&spid={1}&extport={2}&smsid={3}&mobiles={4}&content={5}&sendtime={6}&timestamp={7}&sign={8}&msgfmt={9}";
            string paramStr = string.Format(postDataStr, qiXinTongModel.auth_code, qiXinTongModel.spid, qiXinTongModel.extport, qiXinTongModel.smsid, qiXinTongModel.mobiles, qiXinTongModel.content, qiXinTongModel.sendtime, qiXinTongModel.timestamp, qiXinTongModel.sign, qiXinTongModel.msgfmt);
            string returnVal = HttpHelper.HttpPostRequest("https://qxtapi.js118114.com:9003/SMSController/sendSms.do", paramStr);
            LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "企信通发送短信参数", "", "", "", paramStr);
            LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "企信通发送短信", "", "", "", returnVal);
            if (!string.IsNullOrEmpty(returnVal))
            {
                QiXinTongReturnModel qiXinTongReturnModel = JsonConvert.DeserializeObject<QiXinTongReturnModel>(returnVal);
                return qiXinTongReturnModel;
            }
            return null;
        }

        /// <summary>
        /// 单手机号发送
        /// </summary>
        /// <param name="context"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static QiXinTongReturnModel SendSMS(string context, string phone)
        {
            List<string> phones = new List<string>();
            phones.Add(phone);
            return SendSMS(context, phones.ToArray());
        }

        /// <summary>
        /// URL编码
        /// </summary>
        public static string GetUpperEncode(string encodeUrl, Encoding encode)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < encodeUrl.Length; i++)
            {
                string t = encodeUrl[i].ToString();
                string k = HttpUtility.UrlEncode(t, encode);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString().Replace("(", "%28").Replace(")", "%29");//转义英文的括号
        }

        public static string SHA1Encryption(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytes_in = encode.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                string result = BitConverter.ToString(bytes_out);
                result = result.Replace("-", "");
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错：" + ex.Message);
            }
        }
    }

    public class QiXinTongModel
    {
        public string auth_code { get; set; }

        public string spid { get; set; }

        public string extport { get; set; }

        public string smsid { get; set; }
        /// <summary>
        /// 手机号
        /// </summary>
        public string mobiles { get; set; }
        /// <summary>
        /// 短信内容（签名+短信内容）
        /// </summary>
        public string content { get; set; }

        public string sendtime { get; set; }

        public long timestamp { get; set; }

        public string sign { get; set; }
        public string msgfmt { get; set; }

    }

    public class QiXinTongReturnModel
    {
        public int code { get; set; }
        public string text { get; set; }
        public string smsid { get; set; }
        public string phones { get; set; }
    }


}
